<template>
  <!-- 表单信息 -->
  <div>
    <!-- <div v-if="flowType == 'apply' || flowType == 'draft'" class="title">{{ formData.formName }}</div> -->
    <!-- 发起申请和草稿 或者退回到申请节点 -->
    <div class="formBox">
      <div style="height: 90%;">
        <Parser v-if="formData.formType==1&&formConf" ref="parserForm" :is-detail="isDetail"
                :form-conf="formConf" @submit="submitFormStorage" @errorValid="errorValid" />
        <!-- 当前表单为自定义表单时 -->
        <div v-if="formData.formType==2&&customFormUrl" style="height: 90%;">
          <iframe
            ref="customerFromRef"
            title=""
            class="iframe_body"
            :src="customFormUrl"
            frameborder="0"
            width="100%"
            style="min-height:calc(100vh - 60px - 24px - 600px);height: 99%;"
            scrolling="auto"
          />
        </div>
      </div>
    </div>
    <!-- 根据当前节点是否有抄送权限 -->
    <el-form v-if="iscs" ref="csForm" :model="formData"
             :rules="rules" label-width="100px">
      <el-form-item label="抄送" prop="carbonUser">
        <personSelect
          v-model="formData.carbonUser"
          :params="params"
          :search-user-params="searchUserParams"
          :search-org-params="searchOrgParams"
          :disabled="isdisabled"
          :reappear="true"
          :select-type="'person'"
          :tag-visible="true"
          :api="api"
          @handleSelectData="getSelected"
        />
      </el-form-item>
    </el-form>
    <!-- 申请节点 或 当前节点是退回的节点 需要有按钮提交和重新提交 -->
    <div v-if="isApplyType" class="formbtnsbox">
      <el-button v-preventReClick="3000" @click="handleReset(customFormUrl?2:1)">取消</el-button>
      <el-button v-preventReClick="3000" :loading="stagLoading" @click="addStaging(flowType==='apply'?3:4 )">暂存</el-button>
      <el-button v-preventReClick="3000" :loading="subLoading" type="primary"
                 @click="submitForm(flowType==='apply'?1:0)">提交</el-button>
    </div>
  </div>
</template>
<script>
import Parser from '@/framework/views/developer-center/application-center/application-system/applicationFormDesign/components/parser'
import { draftDetail, formApplyDetail, getDetailById, startFormData, startForm, addOrUpdate, flowableCsRead, doneTaskFormDetal, handleTask, csFormDetail, getManagingOrgUserList, searchUserName, getUserListByUserIds, searchOrgName } from '@/framework/api/affairManage/flowDetail/Config'

export default {
  components: { Parser },
  props: {
    dealform: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      stagLoading: false,
      subLoading: false,
      // 获取表单信息
      formData: {
        carbonUser: '' // 抄送人
      },
      rules: {
        // carbonUser: [
        //   { required: false, message: '请选择抄送人', trigger: 'blur' }
        // ]
      },
      iscs: false, // 判断是否有抄送
      isdisabled: false, // 判断抄送人是否禁用
      formConf: '', // 表单信息
      isApplyType: true, // 判断是否为申请或草稿阶段，判断是否抄送、表单按钮和其他模块是否展示等,
      formType: '1', // 1-设计表单 2-自定义表单
      flowType: '', // 流程类型，为前端自定义
      formConfNeedtodoobg: {}, // 待办任务，当前结点表单详情
      nodeType: 0, // 判断是否为回退节点，0为暂存节点，1为申请节点，2为回退节点，3为申请暂存节点
      status: 0, // 0-发起申请-暂存节点， 1-发起申请-提交节点，2-回退节点，3-草稿-提交节点，4-草稿-暂存节点
      formConfList: [], // 表单回显详情列表
      flowDealDetail: {}, // 流程审批,
      authData: {},
      customFormUrl: '',
      api: { getManagingOrgUserList, searchUserName, searchOrgName, getUserListByUserIds },
      select: [],
      customerDisabled: false,
      params: {
        instanceId: '',
        procdefId: '',
        isFlowCarbonUser: false
      },
      searchUserParams: {
        instanceId: '',
        procdefId: '',
        isFlowCarbonUser: false
      },
      searchOrgParams: {
        instanceId: '',
        procdefId: '',
        isFlowCarbonUser: false
      },
      isDetail: false // 是否是详情页面

    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      /**
     * 1.发起申请: type=apply,deploymentId
     * 2.草稿: type=draft,draftId
     * type=apply/draft ，详情页只显示表单部分（配有取消、暂存、提交按钮），其余部分不显示
     * 3.已发申请: type=applied,id,data
     * 4.抄送: type=cs,id,data,procdefId,nodeId,csId
     * 5.已办: type=doneTask,id,data,taskId
     * type=doneTask,详情显示表单（禁用且没有表单操作按钮）、 操作记录（流程图）
     * 6.待办任务: type=needtodo,id,data,taskId
     * type=needtodo,详情显示表单（禁用且没有表单操作按钮）、 操作记录（流程图）、流程审批
     * 7.流程维护：type=maintain
     * type=maintain,详情只显示操作记录(流程图)
   */
      if (this.$route.query.type) {
        this.flowType = this.$route.query.type
      }
      if (this.$route.query.type === 'apply' && this.$route.query.deploymentId) {
      // 发起申请表单
        this.isApplyType = true
        this.getform(this.$route.query.deploymentId) // 初次发起申请时 获取表单
      } else if (this.$route.query.type === 'draft' && this.$route.query.draftId) {
      // 草稿
        this.isApplyType = true
        this.getDraftformDetail(this.$route.query.draftId) // 草稿 获取表单详情
      } else if (this.$route.query.id) { // this.$route.query.id为 流程实例id
        this.isApplyType = false
        this.isId()
      } else {
      // 审批节点时详情页面表单展示
        this.isApplyType = false
        this.isDetail = true // 禁止从表的按钮
        this.formConf.disabled = true // 禁止编辑修改
      }
    },
    isId() {
      if (this.flowType === 'doneTask' && this.$route.query.id && this.$route.query.taskId) { // 已办-流程详情
        this.isDetail = true
        this.doneTaskDetail(this.$route.query.id, this.$route.query.taskId)
      } else if (this.flowType === 'cs' && this.$route.query.id && this.$route.query.csId) { // 抄送详情
        this.isDetail = true
        this.readed(this.$route.query.csId)
        this.getCsDetail(this.$route.query.id, this.$route.query.procdefId, this.$route.query.nodeId)
      } else if (this.flowType === 'needtodo' && this.$route.query.id) { // 待办- 流程详情
        this.isDetail = false
        this.getflowDealDetail(this.$route.query.id, this.$route.query.taskId)
      } else {
        // 已发申请
        this.getApplyformDetail(this.$route.query.id) // 申请提交后的获取表单详情
      }
    },
    // 抄送回显选人组件的数据
    getSelected(select) {
      this.select = select
    },
    // 渲染自定义表单
    sendMessage(formData, authData) {
      setTimeout(() => {
        this.$nextTick(() => {
          if (this.$refs.customerFromRef) {
            const iframe = this.$refs.customerFromRef
            const content = iframe.contentWindow
            let customerFormData = ''
            if (formData.formData) {
              customerFormData = JSON.parse(formData.formData)
            }
            content.postMessage({
              cmd: 'initialization',
              data: { authData, formData: customerFormData, customerDisabled: this.customerDisabled }
            }, '*')
          }
        })
      }, 1000)
    },
    // 发起申请-获取表单信息
    getform(deploymentId) {
      startFormData({ deploymentId }).then((res) => {
        if (res.data) {
          this.formData = res.data
          this.isDetail = false // 禁止从表的按钮
          this.params.instanceId = this.formData.deploymentId
          this.params.procdefId = this.formData.definitionId
          this.searchUserParams.instanceId = this.formData.deploymentId
          this.searchUserParams.procdefId = this.formData.definitionId
          this.searchOrgParams.instanceId = this.formData.deploymentId
          this.searchOrgParams.procdefId = this.formData.definitionId
          // 内置表单
          if (this.formData.formType === 1 && this.formData.content) {
            this.formConf = JSON.parse(this.formData.content)
            this.formConf.formBtns = false
          } else if (this.formData.formType === 2 && this.formData.formUrl) {
            // 自定义表单
            this.customFormUrl = this.formData.formUrl
            // this.customFormUrl = 'http://localhost:5500/src/framework/views/workflow/flowDetail/components/customerForm.html'
          } else {}
          this.getFormAuth(this.formData, this.formConf)
          if (this.customFormUrl) {
            this.sendMessage(this.formData, this.authData)
          }
          this.iscs = this.formData.cs
          this.$emit('getFormName', this.formData.formName)
        }
      })
    },
    // 申请草稿-获取表单信息
    getDraftformDetail(draftId) {
      draftDetail({ draftId }).then((res) => {
        if (res.data) {
          // 回填数据
          this.formData = res.data
          this.isDetail = false // 禁止从表的按钮
          this.$emit('getFormName', this.formData.formName)
          this.iscs = this.formData.cs
          this.dealList(this.formData)
        }
      })
    },
    // 发起申请和草稿详情页面的提交按钮，首次点击提交 n=1，退回再申请提交n=2
    submitForm(n) {
      this.subLoading = true
      this.status = n
      if (this.formData.formType === 1) {
        this.$nextTick(() => {
          this.$refs.parserForm.submitForm()
        })
      } else if (this.formData.formType === 2) {
        this.saveCustomeFromData(this.status)
      }
    },
    // 发起申请和草稿详情页面的暂存按钮，点击暂存 n=0
    addStaging(n) {
      this.stagLoading = true
      this.status = n
      if (this.formData.formType === 1) {
        this.$refs.parserForm.submitForm('update')
      } else if (this.formData.formType === 2) {
        this.saveCustomeFromData(this.status)
      }
    },
    // 自定义表单提交、暂存
    saveCustomeFromData() {
      const _this = this
      setTimeout(() => {
        const iframe = _this.$refs.customerFromRef
        const content = iframe.contentWindow
        if (_this.authData) {
          content.postMessage({
            cmd: 'submit',
            data: { authData: _this.authData, formData: _this.formData, isSubmit: 1 }
          }, '*')
        }
      }, 2000)
      window.addEventListener('message', _this.handleMessage)
    },
    handleMessage(event) {
      if (event.data.message === 'success') {
        if (this.flowType === 'needtodo') {
          this.$nextTick(() => {
            this.dealform.formData = event.data.data ? JSON.stringify(event.data.data) : this.dealform.formData
            handleTask(this.dealform).then((res) => {
              if (res.success) {
                this.$dtMessage({
                  title: '成功',
                  message: '提交成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.go(-1)
                this.destoryed()
              }
            })
          })
        } else {
          this.formData.formData = JSON.stringify(event.data.data)
          this.formData.variables = {}
          this.formData.processDefinitionId = this.formData.definitionId ? this.formData.definitionId : this.formData.processDefinitionId
          this.formData.definitionId = this.formData.definitionId ? this.formData.definitionId : this.formData.processDefinitionId
          this.submitFormData(this.formData)
        }
      } else {
        this.stagLoading = false
        this.subLoading = false
      }
    },
    // 清除监听
    destoryed() {
      window.removeEventListener('message', this.handleMessage)
    },
    // 当表单校验失败的时候会触发
    errorValid() {
      this.stagLoading = false
      this.subLoading = false
    },
    // 已发起的申请 详情数据回显
    getApplyformDetail(id) {
      formApplyDetail({ instanceId: id }).then((res) => {
        if (res.data) {
          // 回填数据
          this.formData = res.data
          this.isDetail = true // 禁止从表的按钮
          this.iscs = this.formData.cs
          this.select = this.formData.carbonUser
          this.isdisabled = true
          // 表单值的回显
          this.dealList(this.formData)
        }
      })
    },
    // 根据待办任务id 查询任务的流程实例和流程定义等信息
    getflowDealDetail(id, taskId) {
      getDetailById({ instanceId: id, taskId }).then((res) => {
        this.formData = res.data
        this.iscs = false
        this.nodeType = res.data.nodeType
        this.dealList(this.formData)
        this.$emit('getflowDeal', this.formData)
      })
    },
    // 已办任务详情
    doneTaskDetail(id, taskId) {
      doneTaskFormDetal({ instanceId: id, taskId }).then((res) => {
        // 回填数据
        this.formData = res.data
        // 表单值的回显
        this.dealList(this.formData)
      })
    },
    // 抄送事宜-详情
    getCsDetail(id, procdefId, nodeId) {
      csFormDetail({ instanceId: id, procdefId, nodeId }).then((res) => {
        this.formData = res.data
        this.iscs = false
        // 回显表单结构
        this.dealList(this.formData)
      })
    },
    // 循环处理表单详情列表
    dealList(formData) {
      this.$emit('getFormName', this.formData.formName, this.formData.formUrl ? this.formData.formUrl : '')
      try {
        if (formData.formType === 1 && formData.content) {
          this.formConf = JSON.parse(this.formData.content)
          this.formConf.formBtns = false
          this.determineType(formData)
          formData.formData = JSON.parse(formData.formData)
          formData.childFormData = JSON.parse(formData.childFormData)
          // this.fillFormData(this.formConf, JSON.parse(formData.formData))
          this.dealFromJsonValue(formData)
        } else if (formData.formType === 2 && formData.formUrl) {
          this.customFormUrl = this.formData.formUrl
          this.determineType(formData)
        }
        this.isdisabled = true// 抄送人禁止编辑修改
        this.getFormAuth(formData, this.formConf)
        if (this.customFormUrl) {
          this.sendMessage(formData, this.authData)
        }
      } catch (ex) {
      }
    },
    // 判断页面类型
    determineType(formData) {
      if (this.flowType === 'apply' || this.flowType === 'draft' || this.flowType === 'needtodo') {
        this.isFormDisabled(formData)
      } else if (formData.formType === 1 && formData.content) {
        this.formConf.disabled = true // 全内置表单禁止编辑修改
      } else if (formData.formType === 2 && formData.formUrl) {
        this.customerDisabled = true // 全自定义表单禁止编辑修改
      }
    },
    // 判断全表单是否禁用
    isFormDisabled(formData) {
      if (formData.fieldPerms && JSON.parse(formData.fieldPerms).length <= 0) {
        // this.formConf.disabled = true// 全表单禁止编辑修改
        if (this.flowType === 'needtodo' && this.nodeType == 1) {
          this.formConf.disabled = true// 全表单禁止编辑修改
          this.isDetail = true // 禁止从表的按钮
        }
      } else {
        this.formConf.disabled = false // 全表单可编辑修改
      }
    },
    // 表单数据回填
    // fillFormData(form, data) {
    //   const arr = form.fields ? form.fields : form.children
    //   arr.forEach(item => {
    //     if (item.__vModel__) {
    //       const val = data[item.__vModel__]
    //       if (val) {
    //         item.__config__.defaultValue = val
    //       }
    //     } else if (item.__config__?.children?.length > 0) {
    //       this.fillFormData(item.__config__, data)
    //     }
    //   })
    // },

    // 前端 拿到数据后 循环处理成tableOpts格式
    dealFromJsonValue(obj) {
      this.formConf.fields.forEach((cur) => {
        const config = cur.__config__
        if (cur.__vModel__) config.defaultValue = obj.formData[cur.__vModel__]
        if (cur.__config__.children && cur.__config__.layout === 'dtTableDialogRender') {
          // config.tableOpts.tableData = obj.childFormData.map(item => item.tableName === cur.__config__.formId)[0].row
          // config.tableOpts.tableData = obj.childFormData.map(item => item[cur.tableName] === cur.tableName)[0]
          config.tableOpts.tableData = obj.childFormData[cur.tableName]
        }
        this.recursionFcun(cur, obj)
      })
    },
    recursionFcun(data, obj) {
      if ((data.__config__.children && data.__config__.layout === 'rowFormItem') || data.__config__.tableColumnType === 'el-collapse') {
        data.__config__.children.forEach((item) => {
          this.recursionFcun(item, obj)
          if (item.__vModel__) item.__config__.defaultValue = obj.formData[item.__vModel__]
        })
      }
    },
    // 获取表单权限信息
    getFormAuth(formData, formConf) {
      if (formData.fieldPerms && JSON.parse(formData.fieldPerms).length > 0) {
        const fieldPerms = JSON.parse(formData.fieldPerms)
        for (const i of fieldPerms) {
          if (i.childrenColumns && i.childrenColumns.length > 0) {
            i.childrenColumns.map((v) => {
              this.authData[v.dbColumnCode] = v
            })
          } else {
            this.authData[i.dbColumnCode] = i
          }
        }
      } else {
        this.authData = {}
      }
      if (formConf) {
        let prop = ''
        formConf.fields.forEach((item) => {
          if (item.__config__.children && item.__config__.children.length > 0) {
            prop = this.dealData(item)
            // item.__config__.children.forEach((child) => {
            //   prop = child.__vModel__
            //   const itemAuth = this.getFormItemAuth(prop)
            //   if (itemAuth) {
            //     child.__config__.required = itemAuth.required
            //     child.disabled = !(itemAuth.edit)
            //     child.show = itemAuth.show
            //   }
            // })
          } else {
            prop = item.__vModel__
            const itemAuth = this.getFormItemAuth(prop)
            if (itemAuth) {
              item.__config__.required = itemAuth.required
              item.disabled = !(itemAuth.edit)
              item.show = itemAuth.show
            }
          }
        })
      }
    },
    dealData(item) {
      let prop = ''
      item.__config__.children.forEach((child) => {
        prop = child.__vModel__ ? child.__vModel__ : this.dealData(child)
        const itemAuth = this.getFormItemAuth(prop)
        if (itemAuth) {
          child.__config__.required = itemAuth.required
          child.disabled = !(itemAuth.edit)
          child.show = itemAuth.show
        }
      })
      return prop
    },
    getFormItemAuth(prop) {
      if (this.authData[prop]) {
        for (const key in this.authData) {
          if (prop === this.authData[key].dbColumnCode) {
            return this.authData[key]
          }
        }
      }
      // else {
      //   item.__config__.required = false
      //   item.disabled = false
      //   item.show = true
      // }
    },
    // 发起申请和草稿详情页面的取消按钮，表单重置
    handleReset(tag) {
      if (tag === 1) {
        this.$nextTick(() => {
          this.$refs.parserForm.resetForm()
        })
      }
      // 关闭页签回退到上一页面
      this.$router.go(-1)
    },
    // 暂存提交后触发回显数据
    submitFormStorage(valueData) {
      const obj = {
        processDefinitionId: this.formData.definitionId ? this.formData.definitionId : this.formData.processDefinitionId,
        definitionId: this.formData.definitionId ? this.formData.definitionId : this.formData.processDefinitionId,
        formData: valueData.valData ? JSON.stringify(valueData.valData, (key, value) => (typeof value === 'undefined' ? '' : value)) : '',
        childFormData: valueData.formData ? JSON.stringify(this.handleParam(valueData.formData)) : JSON.stringify({}),
        carbonUser: this.formData.carbonUser,
        variables: {},
        isFormProcess: 'Y',
        content: valueData.formData ? JSON.stringify(valueData.formData) : '',
        formUrl: this.formData.formUrl ? this.formData.formUrl : '',
        draftId: this.formData.draftId ? this.formData.draftId : '',
        formName: this.formData.formName,
        formId: this.formData.formId,
        formType: this.formData.formType
      }
      // 待办-提交
      if (this.flowType === 'needtodo') {
        this.$nextTick(() => {
          this.dealform.formData = valueData.valData ? JSON.stringify(valueData.valData) : this.dealform.formData
          this.dealform.childFormData = valueData.formData ? JSON.stringify(this.handleParam(valueData.formData)) : JSON.stringify({})
          handleTask(this.dealform).then((res) => {
            if (res.success) {
              this.$dtMessage({
                title: '成功',
                message: '提交成功',
                type: 'success',
                duration: 2000
              })
              this.$router.go(-1)
            }
          })
        })
      } else {
        this.submitFormData(obj)
      }
    },
    handleParam(formData) {
      return (formData.fields || []).reduce((pre, item) => {
        if (item.__config__.tag === 'dt-table') {
          pre[item.tableName] = item.__config__.tableOpts.tableData
        }
        return pre
      }, {})
    },
    submitFormData(obj) {
      if (this.status === 1 || this.status === 0) {
        // 申请草稿-提交
        if (this.flowType === 'draft') {
          obj.draftId = this.$route.query.draftId // 草稿的提交
        }
        // 发起申请-提交
        startForm(obj).then((res) => {
          if (res.success) {
            this.$dtMessage({
              title: '成功',
              message: '提交成功，可从已发申请查看',
              type: 'success',
              duration: 2000
            })
            this.subLoading = false
            this.$router.go(-1)
            this.destoryed()
          }
        }).catch(() => {
          this.subLoading = false
        })
      } else {
        // 暂存按钮
        if (this.status === 3 || this.status === 4) {
          obj.draftId = this.formData.draftId
        }
        addOrUpdate(obj).then((res) => {
          if (res.success) {
            this.$dtMessage({
              title: '成功',
              message: '暂存成功，已保存至草稿箱',
              type: 'success',
              duration: 2000
            })
            this.stagLoading = false
            this.$router.go(-1)
            this.destoryed()
          }
        }).catch(() => {
          this.subLoading = false
        })
      }
    },
    readed(id) {
      flowableCsRead({ csId: id }).then((res) => {
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.title{
      width: 100%;
      height: 40px;
      font-size: 16px;
      font-family: PingFang SC-Semibold, PingFang SC;
      font-weight: 600;
      color: #131414;
      line-height: 40px;
      margin: 0px auto 16px;
      text-align: center;
    }
    .formBox{
      margin-top: 12px;
      height: 86%;
      overflow-x: hidden; /* 隐藏水平滚动条 */
      overflow-y: scroll; /* 显示垂直滚动条 */
      margin-bottom: 12px;
    }
.formbtnsbox{
  display: flex;
  justify-content: flex-end;
}
::-webkit-scrollbar {
  float: right;
  width: 4px;
  height: 4px;
  background-color: white;
}
</style>
